package com.etc.po;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

@Service
public class HoteliDataApi {
	public  List<com.etc.entity.HotelMessage> findHotel(String cname ,String level) throws IOException, JSONException {
	//public  static void  main(String []args) throws IOException, JSONException {
		List<com.etc.entity.HotelMessage> hms = new ArrayList<>();
		// 请求示例 url 默认请求参数已经做URL编码
		//String url = "http://api01.idataapi.cn:8000/hotel/idataapi?apikey=5YokIQxzT5mzG3UkjLnMtmzXaUmuHG5q2ySETsks0v4RW33UTOjpZYQunmDhsxXW&distance=50000&lon=118.10388605&lat=24.44923061&level=五星级";
		String url = "http://api01.idataapi.cn:8000/hotel/idataapi?apikey=5YokIQxzT5mzG3UkjLnMtmzXaUmuHG5q2ySETsks0v4RW33UTOjpZYQunmDhsxXW&kw="+cname+"&level="+level;

		String json = connectURL(url);
		//System.out.println(json);
		JSONObject jsonText = new JSONObject(json);
		Type type = new TypeToken<List<HotelMessage>>() {}.getType();
		List<HotelMessage> hotelLists = new Gson().fromJson(jsonText.getString("data"), type);
		
		for(int i = 0 ; i < hotelLists.size() ; i++) {
			HotelMessage hj =hotelLists.get(i); 
			
			//	System.out.println("酒店描述："+hj.getDescription()+",名："+hj.getTitle()+",价格："+hj.getPrice()+",图片："+hj.getImageUrls()+",url:"+hj.getUrl());
				com.etc.entity.HotelMessage hm = new com.etc.entity.HotelMessage();
				hm.setHname(hj.getTitle());
				if(hj.getImageUrls()==null||hj.getDescription()==null||hj.getImageUrls().size()<=2||hj.getPrice()<800) {
					continue;
				}
				if(hj.getDescription().replace("�","").substring(8).trim().length()>=150) {
					hm.setHdescription(hj.getDescription().replaceAll("�","").substring(8).trim().substring(0, 149)+"...");
				}else {
					hm.setHdescription(hj.getDescription().replaceAll("�","").substring(8).trim());
				}
				hm.setPrice(hj.getPrice());
				
				hm.setImg(hj.getImageUrls().get(hj.getImageUrls().size()%3));
				hm.setUrl(hj.getUrl());
				hm.setLat(hj.getGeoPoint().getLat());
				hm.setLon(hj.getGeoPoint().getLon());
				hm.setLevel(hj.getLevel());
				
				hms.add(hm);
		
//			System.out.println("酒店描述："+hj.getDescription()+",名："+hj.getTitle()+",价格："+hj.getPrice()+",图片："+hj.getFlatOptions().get(0).getImageUrls()+",url:"+hj.getUrl());
		}
		/*
		for(int i = 0 ; i < hms.size();i++) {
			System.out.println("\n"+hms.get(i));
		}*/
		return hms;
		
		
	}
	
	//java内部调用浏览器获取JSON格式的信息
	public static String connectURL(String dest_url) {
        String rec_string = "";
        URL url = null;
        HttpURLConnection urlconn = null;
        OutputStream out = null;
        BufferedReader rd = null;
        try {
            url = new URL(dest_url);
            urlconn = (HttpURLConnection) url.openConnection();
            urlconn.setReadTimeout(1000 * 30);
            urlconn.setRequestMethod("GET");
            urlconn.setDoInput(true); 
            urlconn.setDoOutput(true);
            out = urlconn.getOutputStream();
           // out.write(commString.getBytes("UTF-8"));
            out.flush(); 
            out.close();
            rd = new BufferedReader(new InputStreamReader(urlconn.getInputStream(),"UTF-8"));
            StringBuffer sb = new StringBuffer();
            int ch;
            while ((ch = rd.read()) > -1)
                sb.append((char) ch);
            rec_string = sb.toString();
        } catch (Exception e) {

            return "";
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (urlconn != null) {
                    urlconn.disconnect();
                }
                if (rd != null) {
                    rd.close();
                }
            } catch (Exception e) {

            }
        }
        return rec_string;
    }
	
}